package com.zjcode.cas.controller;

import com.alibaba.fastjson.JSONObject;
import com.zjcode.cas.model.TkmSysUser;
import com.zjcode.cas.service.TkmSysExService;
import com.zjcode.cas.utils.RedisUtils;
import java.io.IOException;
import java.util.Map;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.jasig.cas.client.authentication.AttributePrincipal;
import org.jasig.cas.client.util.AbstractCasFilter;
import org.jasig.cas.client.validation.Assertion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @ClassName:SinginController
 * @功能：
 * @author：wlei
 * @日期：2022/10/20-02:24
 **/
@Controller
@Slf4j
public class SinginController {

    private static final String URL_CAS_PREFIX = "TKMCodeCer:URL:CAS:";
    @Autowired
    private TkmSysExService sysExService;

    @Autowired
    private RedisUtils redisUtils;

    // 重定向地址
    @Value("${studio.redirect-url}")
    private String redirectUrl;

    @RequestMapping("/singin")
    public void singin(HttpServletRequest request, HttpServletResponse response) {
        //获取用户名并返回

        Assertion assertion = (Assertion) request
            .getSession()
            .getAttribute(AbstractCasFilter.CONST_CAS_ASSERTION);
        AttributePrincipal principal = assertion.getPrincipal();
        Map<String, Object> attributes = principal.getAttributes();
        String name = principal.getName();
        String billNo = "";
        // 当前的name为用户的手机号，此时更具用户的手机号，查询出符合条件的用户
        TkmSysUser user = sysExService.findUserByPhone(name);
        if (user != null) {
            Long id = user.getId();
            // 此时的billNo依旧为加密后的数据
            billNo = sysExService
                .findBySourceId(id.toString())
                .getBillNo();
        }

        JSONObject jobj = new JSONObject();
        jobj.put("name", name);
        jobj.put("billNo", billNo);

        // 获取session的id
        String sessionId = request
            .getSession()
            .getId();

        // 将数据放入缓存总
        String key = URL_CAS_PREFIX + sessionId;
        redisUtils.update(key, jobj.toJSONString());
        log.info("{}->sessionKey:{}", name, key);

        try {
            //response.sendRedirect(
            //    "http://localhost:8000/cancersystem/gateway/home?sessionid=" + sessionId);

            response.sendRedirect(redirectUrl + sessionId);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}
